//
//  ScanViewController.m
//  leo
//
//  Created by 常艳 on 15/9/16.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ScanViewController.h"
#import "FamilyViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Watch.h"
#import "ChooseRelationViewController.h"
#import "BindViewController.h"
#import "AppDelegate.h"
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (strong, nonatomic) UIView *boxView;
@property (strong, nonatomic) CALayer *scanLayer;

-(BOOL)startReading;
-(void)stopReading;

//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic,strong) NSTimer *timer;
@end

@implementation ScanViewController
-(void)dealloc
{
    [self.timer invalidate];
    self.boxView=NULL;
    self.scanLayer=NULL;
    self.captureSession=NULL;
    self.videoPreviewLayer=NULL;
    self.timer=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"扫描手表二维码";
    self.rate=[UIScreen mainScreen].bounds.size.width/320;
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back_icon@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.215f*self.rate, _viewPreview.bounds.size.height * 0.115f*self.rate, _viewPreview.bounds.size.width*self.rate - _viewPreview.bounds.size.width * 0.43f*self.rate, _viewPreview.bounds.size.height*self.rate - _viewPreview.bounds.size.height * 0.65f*self.rate)];
    //_boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.215f, _viewPreview.bounds.size.height * 0.115f, _viewPreview.bounds.size.width- _viewPreview.bounds.size.width * 0.43f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.65f)];
    _boxView.layer.borderColor = [UIColor whiteColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 2);
    _scanLayer.backgroundColor = [UIColor greenColor].CGColor;
    _captureSession = nil;
    [self startReading];
}

- (BOOL)startReading {
    NSError *error;
    
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if(captureDevice==NULL)
    {
        NSLog(@"%@,startReading, captureDevice is null.",scan_tag);
        [LeoMsg showMsg:@"没有视频设备"];
        return NO;
    }
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@,startReading,%@", scan_tag,[error localizedDescription]);
        [LeoMsg showMsg:@"初始化视频设备失败"];
        return NO;
    }
    
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    if(captureMetadataOutput==NULL)
    {
        NSLog(@"%@,startReading,captureMetadataOutput is null", scan_tag);
        [LeoMsg showMsg:@"创建视频输出流失败"];
        return NO;
    }
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    if(_captureSession==NULL)
    {
        NSLog(@"%@,startReading,_captureSession is null", scan_tag);
        [LeoMsg showMsg:@"创建实例会话失败"];
        return NO;
    }
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //5.创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //5.2.设置输出媒体数据类型为QRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    if(_videoPreviewLayer==NULL)
    {
        NSLog(@"%@,startReading,_videoPreviewLayer is null", scan_tag);
        [LeoMsg showMsg:@"实例话预览图层失败"];
        return NO;
    }
    //8.设置图层的frame _viewPreview.layer.bounds
    //[_videoPreviewLayer setFrame:CGRectMake(_viewPreview.layer.bounds.origin.x, _viewPreview.layer.bounds.origin.y, _viewPreview.layer.bounds.size.width*self.rate,  _viewPreview.layer.bounds.size.height*self.rate)];
    [_videoPreviewLayer setFrame:CGRectMake(_viewPreview.layer.bounds.origin.x, _viewPreview.layer.bounds.origin.y, _viewPreview.layer.bounds.size.width*self.rate,  [UIScreen mainScreen].bounds.size.height-_viewPreview.layer.bounds.origin.y)];
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
  
    //9.将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    
    //10.设置扫描范围
    //captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    captureMetadataOutput.rectOfInterest = CGRectMake(0.15f, 0.215f, 0.3f, 0.57f);
    //10.1.扫描框

    
    [_viewPreview addSubview:_boxView];
    
    UIImage *bgimg=[UIImage imageNamed:@"scan111.png"];
    UIImageView *bgimgView=[[UIImageView alloc] initWithImage:bgimg];
    bgimgView.alpha=0.5;
    bgimgView.frame=CGRectMake(_viewPreview.layer.bounds.origin.x, _viewPreview.layer.bounds.origin.y*self.rate, _viewPreview.layer.bounds.size.width*self.rate,_viewPreview.layer.bounds.size.height*self.rate
                               );
    [self.viewPreview addSubview:bgimgView];


    
    [_boxView.layer addSublayer:_scanLayer];
    

     self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [self.timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    

    return YES;
}



-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [self.timer invalidate];
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
    [_boxView removeFromSuperview];
//    _scanLayer=nil;
//    _videoPreviewLayer=nil;
//    _boxView=nil;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [self performSelectorOnMainThread:@selector(analysisData:) withObject:metadataObjects waitUntilDone:YES];
    [self stopReading];
}
-(void)analysisData:(NSArray *)metadataObjects
{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]){
            
            //扫描成功，解析出deviceUid和bindCode和imei号,跳转选手表信息界面
            //NSString *data=@"1233211234567;12345678;137";
            NSString *data=[metadataObj stringValue];
            NSArray * dataArray = [data componentsSeparatedByString:@";"];
            NSString *imei=NULL;
            NSString *bindCode=NULL;
            NSString *deviceUid=NULL;
            if(dataArray!=NULL&&[dataArray count]>=3)
            {
                imei=[dataArray objectAtIndex:0];
                deviceUid=[dataArray objectAtIndex:1];
                bindCode=[dataArray objectAtIndex:2];
            }
            if(deviceUid!=NULL&&[deviceUid intValue]>0&&bindCode!=NULL&&![bindCode isEqualToString:[NSString stringWithFormat:@"%d",BINDERROR_WATCH_NOT_GETBINDCODE]])
            {
                
                Watch *watch=[[Watch alloc] init];
                watch.imei=imei;
                watch.deviceUid=deviceUid;
                watch.bindCode=bindCode;
                ChooseRelationViewController *chooseRelation=[[ChooseRelationViewController alloc] init];
                chooseRelation.watch=watch;
                chooseRelation.type=self.type;
                if(self.type==1)//bind
                {
                    [self.navigationController pushViewController:chooseRelation animated:YES];
                }
                else if(self.type==2)//drop
                {
                    [self.navigationController pushViewController:chooseRelation animated:YES];
                }
                else if(self.type==3)//family
                {
                    
                    UINavigationController *relationNav=[[UINavigationController alloc] initWithRootViewController:chooseRelation];
                    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                    if(mydelegate!=NULL)
                        [mydelegate setNavProperty:relationNav];
                    self.view.window.rootViewController=relationNav;
                    chooseRelation=NULL;
                    [self.navigationController popToRootViewControllerAnimated:YES];

                }

            }
            else//跳转等待绑定界面
            {
                NSLog(@"%@,captureOutput,can not get watch data correct.",scan_tag);
                [self.navigationController popToRootViewControllerAnimated:YES];
                if(deviceUid!=NULL&&[deviceUid intValue]==BINDERROR_WATCH_NOT_REGISTER)
                {
                    [LeoMsg showMsg:BINDERROR_WATCH_NOT_REGISTER_INFO];
                }
                else if(bindCode!=NULL&&[bindCode intValue]==BINDERROR_WATCH_NOT_GETBINDCODE)
                {
                    [LeoMsg showMsg:BINDERROR_WATCH_NOT_GETBINDCODE_INFO];
                }
                else
                {
                    [LeoMsg showMsg:@"您的二维码格式不正确"];
                }
                if(self.type==3)//family
                {
                    BindViewController *bindView=[[BindViewController alloc] init];
                    bindView.type=1;
                    UINavigationController *bindNavigationController=[[UINavigationController alloc] initWithRootViewController:bindView];
                    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                    if(mydelegate!=NULL)
                        [mydelegate setNavProperty:bindNavigationController];
                    self.view.window.rootViewController=bindNavigationController;
                    bindView=NULL;
                }
                else if(self.type==1||self.type==2)//bind drop
                {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
            }
        }
    }
}
- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        
        frame.origin.y += 5;
        
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (BOOL)shouldAutorotate
{
    return NO;
}
-(void)backAction
{
    if(self.type==1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if(self.type==2)
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if(self.type==3)
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
        BindViewController *bindView=[[BindViewController alloc] init];
        UINavigationController *bindNav=[[UINavigationController alloc] initWithRootViewController:bindView];
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL)
            [mydelegate setNavProperty:bindNav];
        self.view.window.rootViewController=bindNav;
        bindView=NULL;
    }
}

-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
@end
